package Servlets;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import aso.upna.cancion.CancionRemota;
import aso.upna.playlist.GenericIterator;
import aso.upna.playlist.GenericList;
import aso.upna.rmi.GetCancionesInterface;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.Collection;
import java.util.Iterator;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import rmi.*;

/**
 *
 * @author eneko
 */
public class Videos extends HttpServlet {
    


    public Vector readEmbeds(String filename)
    {
        String linea,video=null;
        FileReader fr=null;
        BufferedReader bfr=null;
        Vector res=new Vector();
        try{
            fr=new FileReader(filename);
            bfr=new BufferedReader(fr);

            while((linea=bfr.readLine())!=null){
                 video=linea;
                /* if((linea=bfr.readLine()).equals("\n"))
                     continue;
                 else{*/
                        res.add(video.concat(linea));
                 //}
                 //System.out.println(video);
            }
        }
        catch(FileNotFoundException ex){
            ex.printStackTrace();
        }
        catch(IOException ex){
            ex.printStackTrace();
        }

        return res;
    }
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

        Vector s;
        String video="",linea;
        FileReader fr;
        BufferedReader bfr;

        //s=readEmbeds("/Users/chivo/NetBeansProjects/WebAsotify/Embeds.txt");
        //s=readEmbeds("//Volumes//CHIVOX//Users//chivo//NetBeansProjects//WebAsotify//muestra.txt");
            //String p="<object width="+480+" height="+"385"+"><param name="+"movie"+" value="+"http://www.youtube.com/v/U8BWBn26bX0&hl=es_Es&js=1"+"></param><param name="+"allowFullScreen"+"value="+"true"+"></param><param name="+"allowscriptaccess"+"value="+"always"+"></param><embed src="+"http://www.youtube.com/v/U8BWBn26bX0&hl=es_Es&js=1"+" type="+"application/x-shockwave-flash"+ "allowscriptaccess="+"always"+"allowfullscreen="+"true"+"width="+"480" +"height="+"385"+"></embed></object>";
          /*  for(int i=0;i<s.size();i++)
                System.out.println(s.get(i)+"\n");
*/
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        try {
            //Queremos leer los vídeos que hay en el fichero Embeds.txt y construir la web.
            out.println("<html>");

            out.println("<head>");
                out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>");
                out.println("<title>Vídeos</title>");
                out.println("<style type=\"text/css\">");
                    out.println("@import url(style.css);");
                out.println("</style>");
            out.println("</head>");

            out.println("<body>");
                out.println("<div id=\"container\">");
                   out.println("<div id=\"header\">");
                   out.println("</div>");
                   out.println("<ul class=\"menu1\">");
                        out.println("<li><a href=\"./index.jsp\"><b>Inicio</b></a></li>");
                        out.println("<li class=\"current\"><a href=\"ServletYouTube\"><b>Vídeos</b></a></li>");
                        out.println("<li><a href=\"Letras\"><b>Letras</b></a></li>");
                        out.println("<li><a href=\"Imagenes\"><b>Imágenes</b></a></li>");
                    out.println("</ul>");
                    out.println("<div id=\"body\"></br></br>");
                         out.println("<div class=\"box\"></br>");
                            out.println("<div class=\"centrado\">");

                               /* ClientRMI almeta = new ClientRMI();
                                Vector videos=null;
                                try {
                                    videos=almeta.MetadatosRemoto("10.1.1.25",1085,"Videos");
                                } catch (NamingException ex) {
                                    Logger.getLogger(Registrar.class.getName()).log(Level.SEVERE, null, ex);
                                }

                               // out.println("<br/><br/><div class=\"box\">");

                                    for(int i=0;i<videos.size();i++){
                                        out.println(videos.get(i)+"<br/><br/>");
                                    }*/


                                    out.println("<form method=POST action=\"ProcesaVideos\">");
                                                out.println("<select name=cancion size=20>");
                                    try {
                                        GetCancionesInterface ser = (GetCancionesInterface) Naming.lookup("rmi://192.168.1.101:1084/sin_proc");
                                        GenericList users = ser.loggedUsers();
                                        GenericIterator iter = users.getIterator();
                                        ConcurrentHashMap grupos = new ConcurrentHashMap();

                                        while(iter.hasNext())
                                        {
                                            String usr = (String)iter.current();
                                            GenericList aux = ser.getCancionesFrom(usr);
                                            GenericIterator u_iter = aux.getIterator();
                                            while(u_iter.hasNext())
                                            {
                                                CancionRemota c = (CancionRemota)u_iter.current();
                                                String val = c.getMetadatos().getGrupo();

                                                if(!grupos.containsKey(val))
                                                    grupos.put(val, val);

                                                u_iter.next();
                                            }
                                            iter.next();
                                        }

                                        Collection group_col = grupos.values();
                                        Iterator group_iter = group_col.iterator();
                                        while(group_iter.hasNext())
                                        {
                                            String val = (String)group_iter.next();
                                            out.println("<option value=\""+val+"\">"+val);
                                        }

                                    } catch (NotBoundException ex) {
                                        Logger.getLogger(Videos.class.getName()).log(Level.SEVERE, null, ex);
                                    } catch (MalformedURLException ex) {
                                        Logger.getLogger(Videos.class.getName()).log(Level.SEVERE, null, ex);
                                    } catch (RemoteException ex) {
                                        Logger.getLogger(Videos.class.getName()).log(Level.SEVERE, null, ex);
                                    }
                                                out.println("</select><br/><br/>");
                                            out.println("<input type=submit name=info value=\"Ampliar información\">");
                                        out.println("</form>");


                            out.println("</div>");
                        out.println("</div><br/>");
                    out.println("</div></br></br>");
                out.println("</div>");
            out.println("</body>");
        out.println("</html>");
        }
        

        finally {
            out.close();
        }
    }


    

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
